package cn.cleanarch.infra.idp.pms.controller;

import cn.cleanarch.infra.idp.commons.domain.dto.PageResult;
import cn.cleanarch.infra.idp.pms.domain.dto.ProjectCategoryDTO;
import cn.cleanarch.infra.idp.pms.domain.dto.ProjectDTO;
import cn.cleanarch.infra.idp.pms.domain.query.ProjectCategoryQuery;
import cn.cleanarch.infra.idp.pms.domain.query.ProjectQuery;
import cn.cleanarch.infra.idp.pms.service.ProjectCategoryService;
import cn.cleanarch.infra.idp.pms.service.ProjectService;
import cn.cleanarch.infra.idp.web.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目管理控制器
 */
@RestController
@RequestMapping("/pms/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;
    
    @Autowired
    private ProjectCategoryService projectCategoryService;

    /**
     * 分页查询项目
     */
    @GetMapping
    public Result pageQuery(ProjectQuery query) {
        PageResult<ProjectDTO> result = projectService.pageQuery(query);
        return Result.data(result);
    }

    /**
     * 根据ID获取项目
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Long id) {
        cn.cleanarch.infra.idp.pms.domain.entity.Project project = projectService.getById(id);
        // 将实体类转换为DTO，避免Java 8时间类型的序列化问题
        ProjectDTO projectDTO = projectService.convertToDTO(project);
        return Result.data(projectDTO);
    }

    /**
     * 创建项目
     */
    @PostMapping
    public Result create(@RequestBody ProjectDTO dto) {
        ProjectDTO result = projectService.create(dto);
        return Result.data(result);
    }

    /**
     * 更新项目
     */
    @PutMapping
    public Result update(@RequestBody ProjectDTO dto) {
        ProjectDTO result = projectService.update(dto);
        return Result.data(result);
    }

    /**
     * 删除项目
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Long id) {
        Boolean success = projectService.delete(id);
        return Result.data(success);
    }

    /**
     * 获取项目分类列表
     */
    @GetMapping("/categories")
    public Result getProjectCategories() {
        List<ProjectCategoryDTO> categories = projectService.getProjectCategories();
        return Result.data(categories);
    }

    /**
     * 获取用户列表（用于选择负责人）
     */
    @GetMapping("/users")
    public Result getUsers(@RequestParam(value = "username", required = false) String username) {
        List<ProjectCategoryDTO> users = projectService.getUsers(username);
        return Result.data(users);
    }
}